package com.phonebook.controller;


import com.phonebook.entity.ResponseResult;
import com.phonebook.enums.CheckResultEnum;
import com.phonebook.util.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * 图片上传Controller
 */
@RestController
@RequestMapping("image")
@Api(tags = "图片Api")
public class ImageController {


    /**
     * 上传图片
     *
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("upload")
    @ApiOperation("上传图片")
    @ApiImplicitParam(name = "file", value = "上传文件", dataTypeClass = MultipartFile.class, required = true)
    public ResponseResult uploadImage(MultipartFile file) throws Exception {
        Map<String, Object> map = new HashMap<>();
        if (file.isEmpty()) {
            return ResponseResult.error(CheckResultEnum.IMAGE_FAIL.getCode(), CheckResultEnum.IMAGE_FAIL.getMessage());
        }
        String fileName = file.getOriginalFilename();
        String newFileName = DateUtil.getCurrentDateStr() + fileName.substring(fileName.lastIndexOf('.'));
        FileUtils.copyInputStreamToFile(file.getInputStream(), new File("E:\\userImages\\" + newFileName));
        return ResponseResult.success("上传成功", new HashMap<String, Object>(16) {{
            put("title", newFileName);
            put("src", "/image/" + newFileName);
        }});
    }
}
